package epam.bookShelf.textReaders;

import java.io.File;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import epam.bookShelf.bookStuff.Book;
import epam.bookShelf.bookStuff.BookBuilder;
import epam.bookShelf.stuff.Library;

public class BookXMLReader {
    private static final String TITLE       = "title";
    private static final String AUTHOR      = "author";
    private static final String LOCATION    = "location";
    private static final String READED_DATE = "readedDate";
    private static final String DAT         = "dat";
    private static final String ISBN        = "isbn";
    private static final String DESCRIPTION = "description";
    
    Library lib;
    File file;
    
    public BookXMLReader(Library lib, File file) {
        this.lib = lib;
        this.file = file;        
    }
   
    public void parse() {               
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        factory.setAttribute(
                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        		"http://www.w3.org/2001/XMLSchema");


        DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();

	        builder.setErrorHandler(new  ErrorHandler() 
	        {
	            public void warning(SAXParseException e) throws SAXException {
	                System.out.println(e.getMessage());
	            }
	
	            public void error(SAXParseException e) throws SAXException {
	                System.out.println(e.getMessage());
	            }
	
	            public void fatalError(SAXParseException e) throws SAXException {
	                System.out.println(e.getMessage());
	            }
	        });


                                   
            Document doc;
			try {
				doc = builder.parse(file);
	            Element elem = doc.getDocumentElement();
	            
	            NodeList children = elem.getChildNodes();
	            
	            for (int i = 0; i < children.getLength(); i++) {
	                if (children.item(i) instanceof Element) {
	                    Element childEl = (Element) children.item(i);                    
	                    lib.addBook(parseBook(childEl));
	                }
	            }
			} catch (SAXException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}                        
		} catch (ParserConfigurationException e1) {
			e1.printStackTrace();
		}
    }
    
    private Book parseBook(Element elem) {
        BookBuilder builder = new BookBuilder();
        
        NodeList list = elem.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            if (list.item(i) instanceof Element) {
                Element el = (Element) list.item(i);                
                Text textNode = (Text) el.getFirstChild();
                String text = textNode.getNodeValue().trim();
                
                if (el.getTagName().equals(AUTHOR)) {
                    builder.setAuthorName(text);
                } else if (el.getTagName().equals(TITLE)) {
                    builder.setTitle(text);
                } else if (el.getTagName().equals(LOCATION)) {
                    Scanner scan = new Scanner(text);
                    try {
                        builder.setLocationId(scan.nextLong());
                    } catch (InputMismatchException e) {
                        e.printStackTrace();
                    }
                } else if (el.getTagName().equals(READED_DATE)) {
                    Scanner scan = new Scanner(text);
                    try {
                        builder.setReadedDate(scan.nextLong());
                    } catch (InputMismatchException e) {
                        e.printStackTrace();
                    }
                } else if (el.getTagName().equals(DAT)) {
                    Scanner scan = new Scanner(text);
                    try {
                        builder.setDat(scan.nextLong());
                    } catch (InputMismatchException e) {
                        e.printStackTrace();
                    }
                }  else if (el.getTagName().equals(ISBN)) {
                    Scanner scan = new Scanner(text);
                    try {
                        builder.setIsbn(scan.nextLong());
                    } catch (InputMismatchException e) {
                        e.printStackTrace();
                    }
                } else if (el.getTagName().equals(DESCRIPTION)) {
                    builder.setDescription(text);
                }                
            }
        }
        
        return builder.getBook();
    }
}
